package com.yanghui.dtracing.core.classLoader;

import sun.misc.CompoundEnumeration;

import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Enumeration;

public class BreakParentClassLoader extends URLClassLoader {

    public BreakParentClassLoader(URL[] urls,ClassLoader parent) {
        super(urls,parent);
    }

    /**
     * 打破双亲模式，保证自己的类会被自己的classloader加载
     */
    @Override
    protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
        Class<?> c = findLoadedClass(name);
        if (c == null) {
            try {
                c = findClass(name);
            } catch (Exception e) {
            }
        }
        if (c == null) {
            c = super.loadClass(name, resolve);
        }
        return c;
    }

    @Override
    public URL getResource(String name) {
        return findResource(name);
    }


    @Override
    public Enumeration<URL> getResources(String name) throws IOException {
        Enumeration<URL>[] tmp = (Enumeration<URL>[]) new Enumeration<?>[1];
        tmp[0] = findResources(name);
        return new CompoundEnumeration<>(tmp);
    }
}
